package com.imooc.servlet;

import com.imooc.bean.Message;
import com.imooc.entity.Page;
import com.imooc.service.MessageService;
import com.imooc.service.QueryService;
import com.mysql.jdbc.Driver;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

/**
 * 列表页面初始化和查询控制
 */
public class ListServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request,response);
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置编码
        request.setCharacterEncoding("utf-8");
        // 接收页面的值
        String command = request.getParameter("command");
        String description = request.getParameter("description");
        String currentPage = request.getParameter("currentPage");

        // 创建分页对象
        Page page = new Page();
        Pattern pattern = Pattern.compile("[0-9]{1,9}");
        if (currentPage == null || !pattern.matcher(currentPage).matches()) {
            page.setCurrentPage(1);
        } else {
            page.setCurrentPage( new Integer(currentPage));
        }

        QueryService queryService = new QueryService();

        // 查询消息列表并传回页面
        request.setAttribute("messagesList", queryService.queryMessageByPage(command,description,page) );
        request.setAttribute("command", command);
        request.setAttribute("description", description);
        request.setAttribute("page", page);
        request.setAttribute("d","d");
        // 向页面跳转
        request.getRequestDispatcher("/WEB-INF/jsp/back/list.jsp").forward(request,response);
    }
}
